var express = require("express");
var router = express.Router();
var multer = require("multer");
var upload = multer(); // 使用内存存储，仅解析表单

let users = [{ username: "admin", password: "123456" }];

/**
 * @swagger
 * tags:
 *   name: Auth
 *   description: 用户认证
 */

function onlyFormData(req, res, next) {
  if (
    !req.headers["content-type"] ||
    !req.headers["content-type"].startsWith("multipart/form-data")
  ) {
    return res
      .status(415)
      .json({ error: "只支持 multipart/form-data 格式提交" });
  }
  next();
}

/**
 * @swagger
 * /auth/register:
 *   post:
 *     tags: [Auth]
 *     summary: 用户注册
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             $ref: '#/components/schemas/AuthInput'
 *     responses:
 *       200:
 *         description: 注册成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 注册成功
 *       400:
 *         description: 用户名和密码不能为空
 *       409:
 *         description: 用户名已存在
 */
router.post("/register", onlyFormData, upload.none(), function (req, res) {
  const { username, password } = req.body;
  if (!username || !password) {
    return res.status(400).json({ error: "用户名和密码不能为空" });
  }
  const exists = users.find((u) => u.username === username);
  if (exists) {
    return res.status(409).json({ error: "用户名已存在" });
  }
  users.push({ username, password });
  res.json({ message: "注册成功" });
});

/**
 * @swagger
 * /auth/login:
 *   post:
 *     tags: [Auth]
 *     summary: 用户登录
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             $ref: '#/components/schemas/AuthInput'
 *     responses:
 *       200:
 *         description: 登录成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 message:
 *                   type: string
 *                   example: 登录成功
 *       401:
 *         description: 用户名或密码错误
 */
router.post("/login", onlyFormData, upload.none(), function (req, res) {
  const { username, password } = req.body;
  const user = users.find(
    (u) => u.username === username && u.password === password
  );
  if (user) {
    res.json({ message: "登录成功" });
  } else {
    res.status(401).json({ error: "用户名或密码错误" });
  }
});

/**
 * @swagger
 * components:
 *   schemas:
 *     AuthInput:
 *       type: object
 *       properties:
 *         username:
 *           type: string
 *           example: admin
 *         password:
 *           type: string
 *           example: 123456
 */

module.exports = router;
